<?php
class AuthorizeController extends Controller {

	public function indexAction() {
	}

	public function tengxunAction() {
		session_start();
 		 set_include_path(dirname(dirname(__FILE__)) . '/extensions/tengxun/');
 		 require_once 'OpenSDK/Tencent/Weibo.php';
 		 require_once 'appkey.php';
		header('Content-Type: text/html; charset=utf-8');
		OpenSDK_Tencent_Weibo::init($appkey, $appsecret);
		header('Content-Type: text/html; charset=utf-8');
		echo $this->get_server_name();
		echo $callback = $this->get_server_name() . $this->create_url('authorize/callback');
		$request_token = OpenSDK_Tencent_Weibo::getRequestToken($callback);
		$url = OpenSDK_Tencent_Weibo::getAuthorizeURL($request_token);
		header('Location: ' . $url);
	}

	public function callbackAction() {
		session_start();
		header('Content-Type: text/html; charset=utf-8');
 		 set_include_path(dirname(dirname(__FILE__)) . '/extensions/tengxun/');
 		 require_once 'OpenSDK/Tencent/Weibo.php';
 		 require_once 'appkey.php';
		header('Content-Type: text/html; charset=utf-8');
		OpenSDK_Tencent_Weibo::init($appkey, $appsecret);

		//从Callback返回时
		if(OpenSDK_Tencent_Weibo::getAccessToken($_GET['oauth_verifier']))
		{
			//token 入库
			$tengxun_token_model = $this->model('tengxun_token');
			$tokendata = array();
			$tokendata['userid'] = $_SESSION['userid'] ;
			$tokendata['oauth_token'] = $_SESSION['tencent_oauth_token'] ;
			$tokendata['oauth_token_secret'] = $_SESSION['tencent_oauth_token_secret'] ;
			$tokendata['access_token'] = $_SESSION['tencent_access_token'] ;
			$tokendata['openid'] = $_GET['openid'] ;

			if($tengxun_token_model->insert($tokendata)){
				$url = $this->create_url('home/tengxun');
				$this->show_message('授权成功，即将转入腾讯微博',$url,1 );
			}
		}
	}

	public function sinaAction() {
		session_start();
		set_include_path(dirname(dirname(__FILE__)) . '/extensions/sina/');
		include_once( 'config.php' );
		include_once( 'saetv2.ex.class.php' );
		$o = new SaeTOAuthV2( WB_AKEY , WB_SKEY );
		$code_url = $o->getAuthorizeURL( WB_CALLBACK_URL );
		
		$this->assign('authorizeurl' , $code_url);
		$this->display();
	}

	public function sinacallbackAction() {
		session_start();
		set_include_path(dirname(dirname(__FILE__)) . '/extensions/sina/');
		include_once( 'config.php' );
		include_once( 'saetv2.ex.class.php' );
		$o = new SaeTOAuthV2( WB_AKEY , WB_SKEY );
		if (isset($_REQUEST['code'])) {
			$keys = array();
			$keys['code'] = $_REQUEST['code'];
			$keys['redirect_uri'] = WB_CALLBACK_URL;
			try {
				$token = $o->getAccessToken( 'code', $keys ) ;
			} catch (OAuthException $e) {
			}
		}


		if ($token) {
			$_SESSION['token'] = $token;
			$sina_token_model = $this->model('sina_token');

			//token 入库
		$sina_token_model = $this->model('sina_token');
		$sina_token_data = array();
		$sina_token_data['userid'] = $_SESSION['userid'] ;
		// $tokendata['oauth_token'] = $_SESSION['tencent_oauth_token'] ;
		// $tokendata['oauth_token_secret'] = $_SESSION['tencent_oauth_token_secret'] ;
		$sina_token_data['access_token'] = $_SESSION['token']['access_token'] ;
		// $tokendata['openid'] = $_GET['openid'] ;

		if($sina_token_model->insert($sina_token_data)){
			$url = $this->create_url('home/sina');
			$this->show_message('授权成功，即将转入腾讯微博',$url,1 );
		}
			setcookie( 'weibojs_'.$o->client_id, http_build_query($token) );

			$url = $this->create_url('home/sina');
			$this->show_message('新浪微博授权成功，即将转入测试账号',$url,1 );
			// echo '授权完成,<a href="weibolist.php">进入你的微博列表页面</a><br />';

		} else {
			echo "授权失败。";
		}

		echo 'sinacallback';
	}

	//twitter 授权twitter
	public function twitterAction(){
		/* Load and clear sessions */
		session_start();
		set_include_path(dirname(dirname(__FILE__)) . '/extensions/twitter/');
		require_once('config.php');
		require_once('twitteroauth/twitteroauth.php');
		if (CONSUMER_KEY === '' || CONSUMER_SECRET === '') {
		  echo '请先设置Consumer Key以及对于的Consumer Key Secret。如果还没有的话，可以到<a href="http://open.t.sohu.com/index.jsp">http://open.t.sohu.com/index.jsp</a>申请。';
		  exit;
		}


		/* Build TwitterOAuth object with client credentials. */
		$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);
		 
		/* Get temporary credentials. */
		$request_token = $connection->getRequestToken(OAUTH_CALLBACK);

		/* 保存request token，成功获取access token之后用access token代替 */
		$_SESSION['twitter_oauth_token'] = $token = $request_token['oauth_token'];
		$_SESSION['twitter_oauth_token_secret'] = $request_token['oauth_token_secret'];
		 
		switch ($oauth->http_code) {
		  case 200:
		    /* 获取用户认证地址，并且重定向到SOHU */
		    $url = $oauth->getAuthorizeUrl1($token, OAUTH_CALLBACK);
		    // header('Location: ' . $url); 
		    echo '<a href = "'.$url.'" >去授权吧</a>';
		    break;
		  default:
		    /* Show notification if something went wrong. */
		    echo '出错了。。。请重试。';
		}
	}

	// 搜狐微博授权
	public function souhuAction(){
		/* Load and clear sessions */
		session_start();
		set_include_path(dirname(dirname(__FILE__)) . '/extensions/souhu/');
		require_once('config.php');
		if (CONSUMER_KEY === '' || CONSUMER_SECRET === '') {
		  echo '请先设置Consumer Key以及对于的Consumer Key Secret。如果还没有的话，可以到<a href="http://open.t.sohu.com/index.jsp">http://open.t.sohu.com/index.jsp</a>申请。';
		  exit;
		}
		/* 开始申请access token */
		$content = '<a href="./redirect.php">申请Access Token</a>';
		 
		/* Include HTML to display on the page. */
		include('html.inc');
		require_once('oauth/SohuOAuth.php');

		/* 创建SohuOAuth对象 */
		$oauth = new SohuOAuth(CONSUMER_KEY, CONSUMER_SECRET);
		 
		/* 获取request token */
		$request_token = $oauth->getRequestToken(OAUTH_CALLBACK);

		/* 保存request token，成功获取access token之后用access token代替 */
		$_SESSION['oauth_token'] = $token = $request_token['oauth_token'];
		$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];
		 
		switch ($oauth->http_code) {
		  case 200:
		    /* 获取用户认证地址，并且重定向到SOHU */
		    $url = $oauth->getAuthorizeUrl1($token, OAUTH_CALLBACK);
		    // header('Location: ' . $url); 
		    echo '<a href = "'.$url.'" >去授权吧</a>';
		    break;
		  default:
		    /* Show notification if something went wrong. */
		    echo '出错了。。。请重试。';
		}
	}

	//搜狐callbak
	public function souhucallbackAction(){
		/* Start session and load lib */
		session_start();
		set_include_path(dirname(dirname(__FILE__)) . '/extensions/souhu/');
		require_once('oauth/SohuOAuth.php');
		require_once('config.php');

		/* Create TwitteroAuth object with app key/secret and token key/secret from default phase */
		$connection = new SohuOAuth(CONSUMER_KEY, CONSUMER_SECRET, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);

		$oauth_verifier = $this->get_params('oauth_verifier');

		echo $url = $this->create_url('home/souhu') . '?oauth_verifier=' . $oauth_verifier;
		// $this->show_message('搜狐授权成功，回到搜狐首页',$url,1 );
		
	}

	public function renrenAction() {
		session_start();
		set_include_path(dirname(dirname(__FILE__)) . '/extensions/renren/class/');
		// require_once dirname(dirname(__FILE__)) . '/extensions/renren/requires.php';
		require_once 'renrenconfig.inc.php'; 
		

		$url = "https://graph.renren.com/oauth/authorize?client_id={$config->APPID}&response_type=code&scope={$config->scope}&state=a%3d1%26b%3d2&redirect_uri={$config->redirecturi}&x_renew=true" ;

		// header("Location: $url");
		echo $url, '<br/><br/>';
		echo '<a href = "'.$url.'" >登录授权</a>';
	}

	public function renrencallbackAction() {
		session_start();
		set_include_path(dirname(dirname(__FILE__)) . '/extensions/renren/class/');
		$code = $_GET["code"];
		require_once 'renrenconfig.inc.php';
		require_once 'RenrenOAuthApiService.class.php';
		require_once 'RenrenRestApiService.class.php';

		if($code){
			echo '<hr>';
			echo '华丽的分割线';
			echo '<hr>使用code换取accesstoken：<br>';

			//获取accesstoken
			$oauthApi = new RenrenOAuthApiService;
			$post_params = array('client_id'=>$config->APIKey,
			'client_secret'=>$config->SecretKey,
			'redirect_uri'=>$config->redirecturi,
			'grant_type'=>'authorization_code',
			'code'=>$code
			);
			$token_url='http://graph.renren.com/oauth/token';
$access_info=$oauthApi->rr_post_curl($token_url,$post_params);//使用code换取token
//$access_info=$oauthApi->rr_post_fopen($token_url,$post_params);//如果你的环境无法支持curl函数，可以用基于fopen函数的该函数发送请求
$access_token=$access_info["access_token"];
$expires_in=$access_info["expires_in"];
$refresh_token=$access_info["refresh_token"];

if(!empty($access_info))
$_SESSION["access_token"]=$access_token;

echo '$_SESSION[access_token] = '  .  $_SESSION['access_token'] . '<br>';
echo 'access_token:'.$access_token.'<br>';
echo 'expires_in:'.$expires_in.'<br>';
echo 'refresh_token:'.$refresh_token.'<br>';
echo '<hr>';
echo '华丽的分割线';
echo '<hr>使用accesstoken获取登录用户的信息：<br>';
$restApi = new RenrenRestApiService;
//获取用户信息RenrenRestApiService
// $restApi = new RenrenRestApiService;
// $params = array('fields'=>'uid,name,sex,birthday,mainurl,hometown_location,university_history,tinyurl,headurl','access_token'=>$access_token);
// $res = $restApi->rr_post_curl('users.getInfo', $params);//curl函数发送请求
$params = array('fields'=>'uid,name,sex,birthday,mainurl,hometown_location,university_history,tinyurl,headurl','access_token'=>$access_token);
$res = $restApi->rr_post_curl('users.getInfo', $params);//curl函数发送请求

		}
	}
}